package com.ifsmart.mpda;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.HttpAuthHandler;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    WebView webView = null;
    ProgressBar progressBar = null;
    //    String baseIp = "10.36.30.84";
//    String baseUrl = "http://10.36.21.156:8080/smartbi/vision/openresource.jsp?resid=I8aa49517018b5d7a5d7aa67f018c90b85ddc128a&user=admin&password=admin&client=pc&showtoolbar=false";
//    String baseUrl = "http://10.36.20.136:7100/wcb?mode=3&name=%E5%8F%A0%E7%89%87%E8%BD%A6%E9%97%B4CZ22%E7%BA%BF&factoryCode=1011&lineCode=ZPA020&ai=%E6%9E%81%E7%BB%84%E5%AF%B9%E9%BD%90%E5%BA%A6";
//    String baseUrl = "http://10.17.23.45:8081/andon/6%E3%80%8112%E3%80%8119%E3%80%8124%E3%80%8125%E3%80%8126%EF%BC%884%207%EF%BC%89.html?boardId=02";
//    String baseUrl = "http://10.36.30.192:9980/pda/login.html";   //数字化主管
//    String baseUrl = "http://10.36.23.95:31150/dashboard/PC/parkChoose.html";        //无纸化
//   String baseUrl = "http://datacenter.svolt.cn/productionView?autorefresh=1";   //马鞍山
//    String baseUrl = "http://10.36.20.136:7200/battle?encrypt=88f9d986-2e69-47ef-a6b0-bb148ebf8455";  // 红黑榜
    String baseUrl = "http://it.cloudos.svolt.cn/video?company=%E5%8D%97%E4%BA%AC";  // 数字化主管

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.web_view);
        progressBar = findViewById(R.id.progressbar);
        webView.loadUrl(baseUrl);

        webView.addJavascriptInterface(this, "android");
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webViewClient);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true); //允许使用js
        webView.getSettings().setMediaPlaybackRequiresUserGesture(false);

        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
        webSettings.setDomStorageEnabled(true);
        //webSettings.setAppCacheMaxSize(1024*1024*8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        System.out.println("appCachePath" + appCachePath);
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);

        webSettings.setAppCacheEnabled(true);

        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        /**
         * 定时刷新页面
         */
//        new ReloadWebView(this, 3600, webView);
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
//        @Override
//        public void onPageFinished(WebView view, String url) {//页面加wo载完成
//            final String strJS = String.format("javascript:document.getElementById('currentSystemIP').innerHTML='%s';", baseIp);
//            view.evaluateJavascript(strJS, null);
//            progressBar.setVisibility(View.GONE);
//        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("ansen", "拦截url:" + url);
            if (url.equals("http://www.google.com/")) {
                Toast.makeText(MainActivity.this, "国内不能访问google,拦截该url", Toast.LENGTH_LONG).show();
                return true;//表示我已经处理过了
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            Log.e("webview", "onReceivedHttpAuthRequest");
            final WebView mView = view;
            final HttpAuthHandler mHandler = handler;
            final EditText usernameInput = new EditText(MainActivity.this);
            usernameInput.setHint("用户名");
            final EditText passwordInput = new EditText(MainActivity.this);
            passwordInput.setHint("密码");
            passwordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            LinearLayout ll = new LinearLayout(MainActivity.this);
            ll.setOrientation(LinearLayout.VERTICAL);
            ll.addView(usernameInput);
            ll.addView(passwordInput);
            AlertDialog.Builder authDialog = new AlertDialog
                    .Builder(MainActivity.this)
                    .setTitle("身份验证")
                    .setView(ll)
                    .setCancelable(false)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            mHandler.proceed(usernameInput.getText().toString(), passwordInput.getText().toString());
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                            mView.stopLoading();
                        }
                    });
            if (view != null)
                authDialog.show();
        }
    };

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i("ansen", "网页标题:" + title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("ansen", "是否有上一个页面:" + webView.canGoBack());
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    ;


    /**
     * JS调用android的方法
     *
     * @param str
     * @return
     */
    @JavascriptInterface //仍然必不可少
    public void getClient(String str) {
        Log.i("ansen", "html调用客户端:" + str);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //释放资源
        webView.destroy();
        webView = null;
    }

}


